//
//  ACAppDelegate.m
//  ACLiteAVUISDK
//
//  Created by fyanyan on 03/15/2021.
//  Copyright (c) 2021 fyanyan. All rights reserved.
//

#import "ACAppDelegate.h"
#import "ACLoginViewController.h"
#import <IQKeyboardManager.h>
#import <SVProgressHUD.h>
#import <Bugly/Bugly.h>
//#import <CocoaLumberjack/CocoaLumberjack.h>
#import <YKWoodpecker/YKWoodpecker.h>

@interface ACAppDelegate()<UIApplicationDelegate>
@property(nonatomic,strong) ACNavigationController *naVC;
//@property(nonatomic,assign) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@end

@implementation ACAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    BOOL loginStatus = [[ACUserProfileManager shareInstance] getLoginStatus];
    BOOL result = [TRTCLiveRoomIMAction setupSDKWithSDKAppID:ACSDKAPPID listener:[ACUserProfileManager shareInstance]];
    if (!result) {
        return NO;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onkickedOffLine) name:@"onKickedOffline" object:nil];
    if (loginStatus) {
        // 直接进入APP
        ACTabbarViewController *tabVC = [[ACTabbarViewController alloc] init];
        self.naVC = [[ACNavigationController alloc] initWithRootViewController:tabVC];
        self.window.rootViewController = self.naVC;
        [self.window makeKeyAndVisible];
        [[tabVC autoLoginToV2IM] subscribeError:^(NSError * _Nullable error) {
            [self configLoginVC];
        }];
    }else{
        [self configLoginVC];
    }
    
//    [IQKeyboardManager sharedManager] disabledDistanceHandlingClasses =;
    
    //设置弹框显示时不允许交互
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    //设置弹框显示时长
    [SVProgressHUD setMinimumDismissTimeInterval:1.5];
    
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].shouldShowToolbarPlaceholder = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 0.01;

    [Bugly startWithAppId:@"37862517db"];
    
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    [DDLog addLogger:[DDOSLogger sharedInstance]];
    
#ifdef DEBUG
    [[YKWoodpeckerManager sharedInstance] show];
#endif
    [[YKWoodpeckerManager sharedInstance] registerPluginWithParameters:@{@"pluginClassName":@"ACPlayBackMainViewController",@"pluginCategoryName":@"自定义",@"pluginCharIconText":@"UI",@"pluginName":@"精彩回放",@"isSafePlugin":@(NO),@"pluginInfo":@"by_fyy"}];
    return YES;
}
-(void)onkickedOffLine{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"您的账号在其他设备登录，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        DDLogInfo(@"当前用户被挤掉");
        [ACLoginManager requestLogoutWithRequestCallback:^(int code, NSString * _Nullable message) {
            [SVProgressHUD dismiss];
        }];
        
        [self configLoginVC];
        
    }];
    [alertVC addAction:sureAction];
    [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
}
-(void)configLoginVC{
    // 去登录
    ACLoginViewController *loginVC = [[ACLoginViewController alloc] initWithNibName:@"ACLoginViewController" bundle:nil];
    self.naVC = [[ACNavigationController alloc] initWithRootViewController:loginVC];
    self.window.rootViewController = self.naVC;
    [self.window makeKeyAndVisible];
}
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    DDLogInfo(@"url = %@",url);
    NSString *urlStr = url.absoluteString;
    urlStr = [urlStr stringByRemovingPercentEncoding];
    NSMutableString *path = [[NSMutableString alloc] initWithString:urlStr];
    //-----------------判断是否登录
    if ([[ACUserProfileManager shareInstance] getToken]) {
        if([urlStr hasPrefix:@"file:///private"]){
            [path replaceOccurrencesOfString:@"file:///private" withString:@"" options:NSCaseInsensitiveSearch  range:NSMakeRange(0, urlStr.length)];
          //支持上传word\ppt\pdf
            if ([path hasSuffix:@".doc"]|[urlStr hasSuffix:@".docx"]|[urlStr hasSuffix:@".ppt"]|[urlStr hasSuffix:@".pptx"]|[urlStr hasSuffix:@".pdf"]){
                //上传提示
                [self showUploadAlert:path];
            }else{
                [SVProgressHUD showErrorWithStatus:@"不支持上传该格式的文件"];
            }
        }
    }else{
        [SVProgressHUD showErrorWithStatus:@"未登陆"];
    }
    return  YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//    self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
//        [self myBackgroundTask];
//    }];
}

//-(void)myBackgroundTask{
//   //
////    CFRunLoopRef runloopRef = CFRunLoopGetCurrent();
//
//    CFRunLoopObserverContext context = {0,(__bridge void*)self,NULL,NULL};
//    CFRunLoopObserverRef runloopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &runLoopObserverCallBack, &context);
//
//}

//static void runLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
//}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark 上传提示
-(void)showUploadAlert:(NSString *)path{
    NSString *fileName =[[path lastPathComponent] lowercaseString];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"上传%@",fileName] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *uploadAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSFileManager* manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:path]) {
            double fileSize = [[manager attributesOfItemAtPath:path error:nil] fileSize];
            if (fileSize <= (20*1024*1024)) {
                [self uplaodFile:path];
            }else{
                [SVProgressHUD showInfoWithStatus:@"上传文件不能超过20M"];
            }
        }else{
            [SVProgressHUD showInfoWithStatus:@"文件不存在"];
        }
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:uploadAction];
    [self.naVC presentViewController:alert animated:YES completion:nil];
}

//-(void)saveFileToSandBox:(NSString *)path{
//    NSString *fileName =[[path lastPathComponent] lowercaseString];
//    // 沙盒Documents目录
//    NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *localPath = [appDir stringByAppendingPathComponent:fileName];
//    NSError* error = nil;
//    [[NSFileManager defaultManager] copyItemAtPath:path toPath:localPath error:&error];
//    if (error != nil) {
//        [SVProgressHUD showErrorWithStatus:@"文件复制错误"];
//        NSLog(@"%@",error);
//    }else{
//        [self uplaodFile:localPath];
//    }
//}

#pragma mark 上传文件
-(void)uplaodFile:(NSString *)path{
    [SVProgressHUD showProgress:0 status:@"上传中"];
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/material/material"];
    [[ACNetWorkTool shareRequestManager] uploadFile:url filePath:path progress:^(NSProgress * _Nonnull uploadProgress) {
        [SVProgressHUD showProgress:uploadProgress.fractionCompleted status:@"上传中"];
        } success:^(id  _Nonnull responseObject) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showInfoWithStatus:@"上传完成"];
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD showInfoWithStatus:@"上传失败"];
        }];
}

@end
